﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using SummerCore.Models;

namespace SummerCore.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private JwtSettings setting;

        public LoginController(IOptions<JwtSettings> options)
        {
            setting = options.Value;
        }

        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        [HttpPost]
        public MsgModel<string> LoginIn(UserModel user)
        {
            MsgModel<string> msgModel = MsgModel<string>.Failure("");
            try
            {
                if (ModelState.IsValid)
                {
                    if (user.UserName.IndexOf("leon")>-1 && user.Password == "123456")
                    {
                        var claims = new Claim[]
                        {
                        new Claim(ClaimTypes.Name,user.UserName),
                        new Claim(ClaimTypes.Role,user.UserName=="leon"?"admin":"manage")
                        };
                        var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(setting.SecretKey));
                        var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
                        var token = new JwtSecurityToken(
                            setting.Issuer,
                            setting.Audience,
                            claims,
                            DateTime.Now,
                            DateTime.Now.AddMinutes(30),
                            creds);
                        //return Ok(new { Token = new JwtSecurityTokenHandler().WriteToken(token) });
                        string writeToken = new JwtSecurityTokenHandler().WriteToken(token);
                        msgModel = MsgModel<string>.Success(writeToken);
                    }
                    else
                    {
                        msgModel = MsgModel<string>.Failure("账号或密码错误");
                    }
                }
            }
            catch(Exception ex)
            {
                msgModel = MsgModel<string>.Failure(ex.Message);
            }
            return msgModel;
        }
    }
}